package com.liaoyin.travel.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.constant.CommonConstant;
import com.liaoyin.travel.dao.DictBasicMapper;
import com.liaoyin.travel.dao.SmsCodeMapper;
import com.liaoyin.travel.dao.UserTeamMapper;
import com.liaoyin.travel.dao.UsersMapper;
import com.liaoyin.travel.dao.approval.*;
import com.liaoyin.travel.dao.attendance.AttendanceRecordMapper;
import com.liaoyin.travel.dao.attendance.AttendanceUserMapper;
import com.liaoyin.travel.dao.attendance.EquipmentMapper;
import com.liaoyin.travel.dao.report.EventReportMapper;
import com.liaoyin.travel.dao.task.TaskMapper;
import com.liaoyin.travel.dao.team.TeamMapper;
import com.liaoyin.travel.dao.team.WorkerMapper;
import com.liaoyin.travel.entity.*;
import com.liaoyin.travel.entity.attendance.Equipment;
import com.liaoyin.travel.entity.report.EventReport;
import com.liaoyin.travel.entity.task.Task;
import com.liaoyin.travel.entity.task.TaskDetails;
import com.liaoyin.travel.entity.team.Team;
import com.liaoyin.travel.entity.team.TeamWorker;
import com.liaoyin.travel.entity.team.Worker;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.gate.JwtTokenUtil;
import com.liaoyin.travel.service.back.BackUserService;
import com.liaoyin.travel.service.task.TaskDetailsService;
import com.liaoyin.travel.service.task.TaskService;
import com.liaoyin.travel.service.team.TeamService;
import com.liaoyin.travel.service.team.TeamWorkerService;
import com.liaoyin.travel.service.team.WorkerService;
import com.liaoyin.travel.util.*;
import com.liaoyin.travel.view.travelMobileControlSystem.StaffInfoView;
import com.liaoyin.travel.view.user.*;
import com.liaoyin.travel.vo.ChangeManagerVo;
import com.liaoyin.travel.vo.RegisterVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

/**
 * @项目名：
 * @作者：lijing
 * @描述：用户登录注册业务类
 * @日期：Created in 2018/6/8 14:55
 */
@Service
public class UsersService extends BaseService<UsersMapper, Users> {

    /**
     * 默认头像的businessId
     */
    @Value("${default.appHeadPortrait.businessId}")
    private String appHeadPortraitBusinessId;

    @Resource
    AttendanceUserMapper attendanceUserMapper;

    @Resource
    TeamMapper teamMapper;

    @Resource
    ApprovalCardReissueVisibleUserMapper cardReissueVisibleUserMapper;

    @Resource
    ApprovalGoOutVisibleUserMapper goOutVisibleUserMapper;

    @Resource
    ApprovalAskForLeaveVisibleUserMapper askForLeaveVisibleUserMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private SmsCodeMapper smsCodeMapper;

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private EquipmentMapper equipmentMapper;

    @Resource
    private EventReportMapper eventReportMapper;

    @Resource
    private DictBasicMapper dictBasicMapper;

    @Resource
    private WorkerMapper workerMapper;

    @Autowired
    private TeamService teamService;

    @Autowired
    private WorkerService workerService;

    @Autowired
    private UserTeamService userTeamService;

    @Autowired
    private MotionTrackService motionTrackService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private BackUserService backUserService;

    @Autowired
    private TeamWorkerService teamWorkerService;

    @Resource
    private UserTeamMapper userTeamMapper;

    @Resource
    private ApprovalCardReissuePacketApplicantMapper cardReissuePacketApplicantMapper;

    @Resource
    private AskForLeavePacketApplicantMapper askForLeavePacketApplicantMapper;

    @Resource
    private GoOutPacketApplicantMapper goOutPacketApplicantMapper;

    @Resource
    private AttendanceRecordMapper attendanceRecordMapper;

    private Log logger = LogFactory.getLog(this.getClass());

    /****
     * 
         * @方法名：loginByOpenId
         * @描述： 登录
         * @作者： lijing
         * @日期： 2019年7月12日
     */
    public UserInfo loginByOpenId(RegisterVo registerVo) {
        if (registerVo.getPhone() == null) {
            throw new BusinessException("phone.is.null");
        }
        UserInfo userInfo = null;
        boolean b = false;

        if (registerVo.getPassword() == null) {
            throw new BusinessException("password.is.null");
        }
        userInfo = this.mapper.selectUsersByPhone(registerVo.getPhone());
        if (userInfo == null) {
            throw new BusinessException("user.isExist");
        }
        //部门经理
        if (registerVo.getLoginType() == 1 && userInfo.getAssumeOffice() == 2){
            throw new BusinessException("auth.is.error");
        }
        //员工
        if (registerVo.getLoginType() == 2 && userInfo.getAssumeOffice() == 1){
            throw new BusinessException("auth.is.error");
        }

        if (userInfo != null && !"".equals(userInfo)) {
            System.err.println("userInfo.getPassword()="+userInfo.getPassword());
            System.err.println("registerVo.getPassword()="+registerVo.getPassword());
            System.err.println("MD5Util.createPassword="+MD5Util.createPassword(registerVo.getPassword(),userInfo.getId()));
            if (MD5Util.createPassword(registerVo.getPassword(),userInfo.getId()).equals(userInfo.getPassword())) {
                b = true;
            } else {
            	logger.debug(userInfo.getId()+"密码错误");
                throw new BusinessException("password.is.error");
            }
        }
        if (b) {
        	userInfo.setPassword(null);
            //生成token
            String token = JwtTokenUtil.createJWT(userInfo.getPhone(), userInfo.getId(), userInfo.getNickName(), null, null, null, 24 * 24 * 60 * 60 * 1000, "123456");
            userInfo.setToken(token);
            //查询用户的部门信息
            List<UserTeam> userTeamList = this.userTeamService.selectUserTeam(userInfo.getId(), "");
            userInfo.setUserTeamList(userTeamList);
            userTeamList=null;
            //将用户信息保存到redis
            RedisUtil.set(userInfo.getPhone() + "#" + userInfo.getId(), JsonUtil.getJsonString(userInfo), jwtTokenUtil.getExpiration());
        } else {
            throw new BusinessException("user.isExist");
        }
        return userInfo;
    }

    /**
    　* @description: TODO 指纹登录根据用户ID
    　* @param [uid]
    　* @return com.liaoyin.travel.bean.UserInfo
    　* @throws
    　* @author privatePanda777@163.com
    　* @date 2019/7/29 12:46
    　*/
    public UserInfo loginByFingerprint(String uid){
        if (null == uid){
            throw new BusinessException("id.is.null");
        }
        UserInfo userInfo= null;
        userInfo = this.mapper.selectUsersByFingerprint(uid);
        if(userInfo == null) {
        	throw new BusinessException("user.isExist");
        }
        userInfo.setPassword(null);
        String token = JwtTokenUtil.createJWT(userInfo.getId(),userInfo.getNickName(),null,null,null,null,24 * 24 * 60 * 60 * 1000,"123456");
        userInfo.setToken(token);
        //查询用户的部门信息
        List<UserTeam> userTeamList = this.userTeamService.selectUserTeam(userInfo.getId(), "");
        userInfo.setUserTeamList(userTeamList);
        userTeamList=null;
        //将用户信息保存到redis
        RedisUtil.set(userInfo.getPhone() + "#" + userInfo.getId(), JsonUtil.getJsonString(userInfo), jwtTokenUtil.getExpiration());
        return userInfo;
    }

    /*****
     * 
         * @方法名：selectMailListList
         * @描述： 查询我的通讯录 --前端
         * @作者： lijing
         * @日期： 2019年7月16日
     */
    public List<Users> selectMailListList(Integer num,Integer size){
    	
    	UserInfo user = PartyUtil.getCurrentUserInfo();
        if (user == null) {
            throw new BusinessException("not.login");
        }
    	/*if(user.getTeamId() == null) {
    		throw new BusinessException("team.is.null");
    	}*/
        if(user.getUserTeamList()==null || user.getUserTeamList().size() == 0) {
        	throw new BusinessException("team.is.null");
        }
        StringBuffer teamId = new StringBuffer();
        for(UserTeam u:user.getUserTeamList()) {
        	teamId.append(u.getTeamId()+",");
        }
    	PageHelper.startPage(num,size);
        System.out.println(teamId.toString());
    	List<Users> list = this.mapper.selectUsersListOnTeamById(teamId.toString());
    	if(list !=null &&list.size() >0) {
    		for (Users u : list) {
                u.setFileUpload(FileUploadUtil.getFileUpload(u.getHeadPicId()));
            }
    	}
        
    	return list;
    }

    public int selectUsersCnt(String teamId){
        return this.mapper.selectUsersCnt(teamId);
    }
    
    /***8
     * 
         * @方法名：changePassword
         * @描述： 修改密码 --前端
         * @作者： lijing
         * @日期： 2019年7月23日
     */
    public void changePassword(String oldPassWord,String newPassword,String confirmPassWord) {
    	
    	if(oldPassWord==null) {
    		throw new BusinessException("oldPassWord.is.null");
    	}
    	if(newPassword==null) {
    		throw new BusinessException("newPassword.is.null");
    	}
    	if(confirmPassWord==null) {
    		throw new BusinessException("confirmPassWord.is.null");
    	}
    	if(!newPassword.equals(confirmPassWord)){
        	throw new BusinessException("confirmPassWord.is.error");
    	}
    	UserInfo user = PartyUtil.getCurrentUserInfo();
    	if(user == null) {
    		throw new BusinessException("not.login");
    	}
    	Users userInfo = this.mapper.selectByPrimaryKey(user.getId());
    	if(!userInfo.getPassword().equals(MD5Util.createPassword(oldPassWord,userInfo.getId()))) {
    		throw new BusinessException("oldPassWord.is.error");
    	}
    	userInfo.setPassword(MD5Util.createPassword(newPassword,userInfo.getId()));
    	this.mapper.updateByPrimaryKeySelective(userInfo);
    	logger.info(user.getPhone()+"修改密码,原密码:"+userInfo.getPassword()+",新密码:"+newPassword+",修改时间:"+DateUtil.getCurrentTime4Str());
    	RedisUtil.del(userInfo.getPhone() + "#" + userInfo.getId());
    }
    
    

    /**
     * @Description: 我的信息
     * @Author: rzy
     * @Date: 2018/11/23
     */
    public UserInfo selectMyUserInfo() {
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if (user == null) {
            throw new BusinessException("not.login");
        }
        return user;
    }
    /**
     * @Description: 生成平台唯一推广码
     * @Author: rzy
     * @Date: 2018/12/5
     */
    public String creatPromotionCode() {
        String sources = "0123456789ABCDEFGHIZKLMNOBQRSTUVWSYZ";
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        for (int j = 0; j < 6; j++) {
            flag.append(sources.charAt(rand.nextInt(35)) + "");
        }
        return flag.toString();
    }

    /**
     * @方法名：creatOnlyAccount
     * @描述： 生成平台唯一账号
     * @作者： lijing
     * @日期： 2018年11月8日
     */
    public String creatOnlyAccount(String userType, int num) {
        String account = "";
        if ("1".equals(userType)) {
            account += "6";
        } else {
            account += "3";
        }
        account += DateUtil.getCurrentyyyymmddNow() + DateUtil.randomInterceptionMillisecond(num);
        //判断是否唯一
        int k = this.mapper.selectByAccountCount(account);
        if (k == 0) {
            return account;
        } else {
            return creatOnlyAccount(userType, num++);
        }
    }


    /**
     * @方法名：selectUsersById
     * @描述： 根据id查询用户详情
     * @作者： lijing
     * @日期： 2018年11月9日
     */
    public Users selectUsersById(String id) {
        if (id == null) {
            throw new BusinessException("id.is.null");
        }
        Users u = this.mapper.selectByPrimaryKey(id);
        if (u != null) {
            FileUpload f = FileUploadUtil.getFileUpload(u.getHeadPicId());
            if (f != null && !"".equals(f)) {
                u.setHeadUrl(CommonConstant.FILE_SERVER + f.getFilePath());
                f = null;
            }
            List<UserTeam> list = this.userTeamService.selectUserTeam(u.getId(), "");
            u.setUserTeamList(list);
            list = null;
        }
        return u;
    }

    /**
     * @方法名：selectUsersListOnNickName
     * @描述： 查询所有用户的昵称等信息
     * @作者： lijing
     * @日期： 2018年11月20日
     */
    public List<Users> selectUsersListOnNickName(List<String> userIdList) {
        List<Users> list = this.mapper.selectUsersListOnNickName(userIdList);
        return list;
    }
    
    /****
     * 
         * @方法名：selectUsersList
         * @描述： 查询前端用户列表
         * @作者： lijing
         * @日期： 2019年7月16日
     */
    public List<Users> selectUsersList(Integer num, Integer size, String phone,String userType,
    		String nickName,String teamId,String assumeOffice,String workId,String isUsing){

        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

    	PageHelper.startPage(num,size);
    	List<Users> list = this.mapper.selectUsersList(phone, userType, nickName, teamId, assumeOffice, workId, isUsing,scenicId);
    	
    	return list;
    }
    

    /****
	 * 
	     * @方法名：selectUsersListOnTeamById
	     * @描述： 查询部门下的所有员工信息
	     * @作者： lijing
	     * @日期： 2019年7月15日
	 */
	public List<Users> selectUsersListOnTeamById(String teamId){
		if(teamId==null) {
			throw new BusinessException("team.is.null");
		}
		List<Users> list = this.mapper.selectUsersListOnTeamById(teamId);
		return list;
	}
	
	/***
	 * 
	     * @方法名：selectAllTheTreamUserId
	     * @描述： 查询某一个部门下的所有员工的id
	     * @作者： lijing
	     * @日期： 2019年8月21日
	 */
	public List<String> selectAllTheTreamUserId(String teamId){
		
		List<Users> list = this.mapper.selectUsersListOnTeamById(teamId);
		List<String> userList = new ArrayList<String>();
		if(list !=null && list.size() >0) {
			list.stream().forEach((u) ->{
				if(u != null) {
					userList.add(u.getId());
				}
			});
		}
		return userList;
	}
	
	/****
	 * 
	     * @方法名：selectselectUsersListBybusinessIds
	     * @描述： 查询多个部门下的人员
	     * @作者： lijing
	     * @日期： 2019年7月25日
	     * @param type  :1： 查询部门 2：查询工种
	 */
	public List<Users> selectselectUsersListBybusinessIds(String type,String[] businessId){
		
		List<Users> list = this.mapper.selectselectUsersListBybusinessIds(type, businessId);
		return list;
	}
	
	/***
	 * 
	     * @方法名：selectUsersWorkList
	     * @描述： 查询所有工种的用户id
	     * @作者： lijing
	     * @日期： 2019年8月21日
	 */
	public List<String> selectUsersWorkList(String workId){
		
		List<String> userList = new ArrayList<String>();
		if(workId !=null) {
			List<Users> list =selectselectUsersListBybusinessIds(VariableConstants.STRING_CONSTANT_2, workId.split(","));
			if(list !=null && list.size() >0) {
				list.stream().forEach((u) ->{
					if(u !=null) {
						userList.add(u.getId());
					}
				});
			}
		}
		return userList;
	}
	
	
	/*****
	 * 
	     * @方法名：selectUsersIdListByManager
	     * @描述： 查询部门下经理人的id
	     * @作者： lijing
	     * @日期： 2019年7月24日
	 */
	public List<String> selectUsersIdListByManager(String teamId){
		
		List<Users> list = selectUsersListOnTeamById(teamId);
		List<String> managerList = new ArrayList<String>();
		if(list !=null && list.size() >0) {
			list.stream().forEach((u) ->{
				if(u.getAssumeOffice() !=null && u.getAssumeOffice().intValue() == 1) {
					managerList.add(u.getId());
				}
			});
		}
		return managerList;
	}
	 /**
   　* @description: TODO 新增或更新用户信息
   　* @param [users]
   　* @return int
   　* @throws
   　* @author privatePanda777@163.com
   　* @date 2019/7/24 16:46
   　*/
	@Transactional(rollbackFor=BusinessException.class)
	public int insertOrUpdateUsers(Users users) throws ParseException {

	    //查询当前用户的景区id作为新增用户的景区id
        UserInfo curentUser = PartyUtil.getCurrentUserInfo();
        if(curentUser == null) {
            throw new BusinessException("not.login");
        }
        System.err.println("当前登录用户的scenicId="+curentUser.getScenicId());
        /** 景区id **/
        String scenicId = curentUser.getScenicId();

        if (null !=  users.getNickName() && users.getNickName().length()>20){
            throw new BusinessException("string.is.toLong");
        }
        String phone = users.getPhone();
        if(StringUtils.isNotBlank(users.getPhone()) && PhoneUtil.isPhone(phone) == null){
            throw new BusinessException("phone.is.mistake");
        }

        List<Users> usersList = this.mapper.selectUsersByPhoneAndId(phone,users.getId());
        if (usersList.size() > 0){
            throw new BusinessException("phone.is.exist");
        }

        //原部门经理id
        String originalDirectorId = users.getOriginalDirectorId();

        String identityCard = users.getIdentityCard();
        //身份证有效性验证
        if(StringUtils.isNotBlank(identityCard)&&!ValidateUtil.validateIDCard(identityCard)){
            throw new BusinessException("wrong.id.number");
        }

        //工号
        String workerNum = users.getWorkerNum();
        //验证工号不能重复
        this.verifyWorkerNumReDo(workerNum,scenicId,users.getId());

        //邮箱地址正则校检
        String emailAddress = users.getEmailAddress();
        if(emailAddress!=null && !"".equals(emailAddress)){
            if(!RegExpValidatorUtils.isEmail(emailAddress)){
                throw new BusinessException("mailbox.is.error");
            }
        }

	    int result;
        /**  更新 */
       if(users.getId() !=null && !"".equals(users.getId())) {

           //验证身份证号码不能重复
           List<Users> oldUserList = this.mapper.selectUserByIdentityCardAndUserId(identityCard,users.getId());
           if(oldUserList.size()>0){
               throw new BusinessException("identityCard.is.exist");
           }
           users.setAccount(users.getPhone());
           /*if (null != users.getPassword() && !"".equals(users.getPassword())) {
               users.setPassword(MD5Util.createPassword(users.getPassword(),users.getId()));
           }*/
           users.setPassword(null);
           if (users.getFileUpload() != null && !"".equals(users.getFileUpload())){
               users.setHeadPicId(FileUploadUtil.saveFileUpload(users.getFileUpload(),users.getId()));
           }

           result = this.mapper.updateByPrimaryKeySelective(users);
           if(users.getUserTeamList()!= null && users.getUserTeamList().size() >0) {
        	   this.userTeamService.insertOrUpdate(users.getId(), users.getUserTeamList(),originalDirectorId);
    	   }
       }else {
           /**  新增 */
           if (users.getFileUpload() != null){
               users.setHeadPicId(FileUploadUtil.saveFileUpload(users.getFileUpload(),users.getId()));
           }

           //验证身份证号码不能重复
           List<Users> oldUserList = this.mapper.selectUserByIdentityCard(identityCard);
           if(oldUserList.size()>0){
               throw new BusinessException("identityCard.is.exist");
           }

           //当前登录账号类型
            String accountType = curentUser.getAccountType();

           if(accountType.equals("1")){
               //当前是景区管理员登录
               users.setEmptype("1");
           }else if(accountType.equals("2")){
               //当前是机构管理员登录
               users.setEmptype("2");
               users.setOrganType(curentUser.getOrganType());
           }

           String salt = UUIDUtil.getUUID();
           users.setId(salt);
           users.setAccount(users.getPhone());
           users.setDelFlag((short)0);
           users.setPassword(MD5Util.createPassword(ParamUtil.getValue("defaultPaword"),salt));
           users.setCreateTime(new Date());
           users.setIsUsing((short)1);
           users.setScenicId(scenicId);
           //新增部门
           this.userTeamService.insertOrUpdate(salt, users.getUserTeamList(),originalDirectorId);
           result = this.mapper.insertSelective(users);
       }
       return result;
   }

    /**
     * @方法名：verifyWorkerNumReDo
     * @描述： 验证工号是否重复，若重复则会抛异常
     * @作者： kjz
     * @日期： Created in 2020/2/27 17:46
     */
    private void verifyWorkerNumReDo(String workerNum, String scenicId, String userId) {
        List<Users> usersList = this.mapper.selectUsersByWorkNum(workerNum,scenicId,userId);
        if(usersList!=null && usersList.size()>0){
            throw new BusinessException("worker.is.exist");
        }
    }

    /**
   　* @description: TODO 根据用户ID删除用户
   　* @param [uid]
   　* @return int
   　* @throws
   　* @author privatePanda777@163.com
   　* @date 2019/7/24 17:09
   　*/
   public int deleteUsersById(String uid){
	    int i;
	    Users users = new Users();
	    users.setId(uid);
	    users.setDelFlag((short) 1);
	    i = this.mapper.updateByPrimaryKey(users);
       return i;
   }
	/****
	 * 
	     * @方法名：judgeThisUserInTeam
	     * @描述： 判断某个员工是否在某部门下
	     * @作者： lijing
	     * @日期： 2019年7月24日
	 */
	public Boolean judgeThisUserInTeam(String teamId,String userId) {
		
		boolean b = false;
		List<Users> list = selectUsersListOnTeamById(teamId);
		if(list != null && list.size() >0) {
			for(Users u :list) {
				if(u.getId().equals(userId)) {
					b = true;
					break;
				}
			}
		}
		
		return b;
	}

    /**
     * @方法名：importUsersForExcel
     * @描述： excel导入用户数据
     * @作者： kjz
     * @日期： Created in 2020/4/3 11:55
     */
    @Transactional(rollbackFor=BusinessException.class)
	public int importUsersForExcel(String fileName,MultipartFile file) {

        Map<String,String> propertyMap = new LinkedHashMap<>();
        propertyMap.put("用户类型*","userTypeDisplay");
        propertyMap.put("是否启用*","isUsingDisplay");
        propertyMap.put("员工姓名*","nickName");
        propertyMap.put("性别*","sexDisplay");
        propertyMap.put("手机号*","phone");
        propertyMap.put("身份证号*","identityCard");
        propertyMap.put("所属部门*","industryTitle");
        propertyMap.put("员工工种(管理端不填)*","workName");
        propertyMap.put("工号*","workerNum");
        propertyMap.put("邮箱地址","emailAddress");

        //生成工作簿
        Workbook wb = ExcelUtil.createWorkBook(fileName,file);
        //工作表
        Sheet sheet = wb.getSheetAt(0);
        //标题行(从第一行开始)
        Row titleRow = sheet.getRow(1);
        //标题行有几列
        int headingLength = titleRow.getLastCellNum();

        //标记好excel的标题和值的顺序
        Map<Integer,String> titleRecord = new LinkedHashMap<>();
        Map<Integer,String> valueRecord = new LinkedHashMap<>();
        for(int i = 0;i<headingLength;i++){

            Cell cell = titleRow.getCell(i);

            for(Map.Entry<String, String> entry : propertyMap.entrySet()){
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();
                if(mapKey.equals(cell.getStringCellValue())){
                    mapKey=mapKey.replace("*","");
                    titleRecord.put(i,"【"+mapKey+"】");
                    valueRecord.put(i,mapValue);
                }
            }

        }

        int result = 0;
        //遍历工作表(从第5行开始)
        for (int r = 4; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            //如果整行数据为空
            if (ExcelUtil.isAllRowEmpty(row,headingLength)){
                continue;
            }
            //遍历每一个单元格
            JSONObject jsonObject = new JSONObject();
            for(int j=0;j<headingLength;j++){
                Cell cell = row.getCell(j);
                String cellValue = ExcelUtil.getCellValue(cell);
                /*if(StringUtil.isBlank(cellValue)){
                    throw new BusinessException("import.failure","第"+(r+1)+"行"+titleRecord.get(j)+"不能为空");
                }*/
//                System.err.println("属性："+valueRecord.get(j));
//                System.err.println("值："+cellValue);
                jsonObject.put(valueRecord.get(j),cellValue);
            }
            Users users = JSONObject.parseObject(jsonObject.toString(),Users.class);
            System.err.println("json="+jsonObject.toString());
            System.err.println("users="+users);
            result += insertUserByExcel(users,r+1);

        }
        return result;
    }

    /**
     * @方法名：insertUserByExcel
     * @描述： 通过excel导入的方式新增用户
     * @作者： kjz
     * @日期： Created in 2020/4/3 12:13
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertUserByExcel(Users users, Integer rownum) {
        //查询当前用户的景区id作为新增用户的景区id
        UserInfo curentUser = PartyUtil.getCurrentUserInfo();
        if(curentUser == null) {
            throw new BusinessException("not.login");
        }
        System.err.println("当前登录用户的scenicId="+curentUser.getScenicId());
        /** 景区id **/
        String scenicId = curentUser.getScenicId();

        //当前登录账号类型
        String accountType = curentUser.getAccountType();

        if(accountType.equals("1")){
            //当前是景区管理员登录
            users.setEmptype("1");
        }else if(accountType.equals("2")){
            //当前是机构管理员登录
            users.setEmptype("2");
            users.setOrganType(curentUser.getOrganType());
        }

        /******** 用户类型 ********/

        //用户类型Display
        String userTypeDisplay = users.getUserTypeDisplay();
        System.err.println("userTypeDisplay="+userTypeDisplay);
        if(userTypeDisplay == null || userTypeDisplay.isEmpty()){
            throw new BusinessException("import.failure","导入失败(第"+rownum+"行,用户类型未填写)");
        }

        if(!"管理端".equals(userTypeDisplay) && !"员工端".equals(userTypeDisplay)){
            throw new BusinessException("import.failure","第"+rownum+"行,用户类型只能传入【员工端】或【管理端】");
        }

        String userType = userTypeDisplay.equals("员工端")?"1":"2";

        /******** 是否启用 ********/
        //是否启用Display
        String isUsingDisplay = users.getIsUsingDisplay();
        System.out.println("isUsingDisplay="+isUsingDisplay);
        if(isUsingDisplay==null || isUsingDisplay.isEmpty()){
            throw new BusinessException("import.failure","导入失败(第"+rownum+"行,是否启用未填写)");
        }
        if(!"是".equals(isUsingDisplay) && !"否".equals(isUsingDisplay)){
            throw new BusinessException("import.failure","第"+rownum+"行,是否启用只能传入【是】或【否】");
        }

        Short isUsing = isUsingDisplay.equals("是")?Short.valueOf("1"):Short.valueOf("0");

        /******** 员工姓名 ********/
        //员工姓名
        String nickName = users.getNickName();

        if(nickName==null || nickName.isEmpty()){
            throw new BusinessException("import.failure","导入失败(第"+rownum+"行,员工姓名未填写)");
        }

        /******** 性别 ********/
        //性别
        String sexDisplay = users.getSexDisplay();
        if(sexDisplay==null || sexDisplay.isEmpty()){
            throw new BusinessException("import.failure","导入失败(第"+rownum+"行,性别未填写)");
        }

        if(!"男".equals(sexDisplay) && !"女".equals(sexDisplay)){
            throw new BusinessException("import.failure","第"+rownum+"行,性别只能传入【男】或【女】");
        }
        Short sex = sexDisplay.equals("男")?Short.valueOf("1"):Short.valueOf("2");


        /******** 手机号码 ********/
        //联系电话
        String phone = users.getPhone();

        if(phone==null || phone.isEmpty()){
            throw new BusinessException("import.failure","导入失败(第"+rownum+"行,手机号码未填写)");
        }

        if (phone.indexOf(" ") != -1) {
            throw new BusinessException("import.failure","导入失败(第"+rownum+"行,手机号码不能包含空格)");
        }

        if(PhoneUtil.isPhone(phone) == null){
            throw new BusinessException("import.failure","导入失败(第"+rownum+"行,手机号码格式错误,号码无效)");
        }

        List<Users> usersList = this.mapper.selectUsersByPhoneAndId(phone,null);
        if (usersList.size() > 0){
            throw new BusinessException("import.failure","导入失败(第"+rownum+"行,手机号码已存在,不能重复");
        }

        /******** 身份证号 ********/
        //身份证号
        String identityCard = users.getIdentityCard();
        if(identityCard==null || identityCard.isEmpty()){
            throw new BusinessException("import.failure","导入失败(第"+rownum+"行,身份证号未填写)");
        }

        //验证身份证号码不能重复
        List<Users> oldUserList = this.mapper.selectUserByIdentityCard(identityCard);
        if(oldUserList.size()>0){
            throw new BusinessException("identityCard.is.exist");
        }


        /******** 所属部门 ********/
        //部门名称
        String industryTitle = users.getIndustryTitle();
        if(industryTitle==null || industryTitle.isEmpty()){
            throw new BusinessException("import.failure","导入失败(第"+rownum+"行,所属部门未填写)");
        }
        Team team = this.teamService.selectTeamByName(industryTitle);
        if(team==null){
            throw new BusinessException("import.failure","导入失败,第"+rownum+"行,所属部门不存在,请填入正确的部门名字！");
        }
        //部门id
        String teamId = team.getId();

        //组装部门信息 参数
        List<UserTeam> userTeamList = new ArrayList<>();
        UserTeam userTeam = new UserTeam().setTeamId(teamId)
                .setAssumeOffice(userType.equals("1")?Short.valueOf("2"):Short.valueOf("1"));
        userTeamList.add(userTeam);

        /******** 员工工种 ********/
        //只有员工端才会填入员工工种字段
        if(userType.equals(VariableConstants.STRING_CONSTANT_1)){
            //工种名字
            String workName = users.getWorkName();
            if(workName==null || workName.isEmpty()){
                throw new BusinessException("import.failure","导入失败(第"+rownum+"行,员工工种未填写)");
            }
            Worker worker = this.workerService.selectworkerByName(workName);
            if(worker==null){
                throw new BusinessException("import.failure","导入失败(第"+rownum+"行,该工种不存在,请填入正确的工种名)");
            }

            TeamWorker teamWorker = this.teamWorkerService.selectTeamWorkerByTeamIdAndWorkerId(teamId,worker.getId());

            if(teamWorker==null){
                throw new BusinessException("import.failure","第"+rownum+"行,【"+industryTitle+"】部门没有关联【"+workName+"】工种");
            }

            users.setWorkId(worker.getId());
        }

        /******** 工号 ********/
        //工号
        String workerNum = users.getWorkerNum();
        if(workerNum==null || workerNum.isEmpty()){
            throw new BusinessException("import.failure","导入失败(第"+rownum+"行,工号未填写)");
        }

        //验证工号不能重复
        this.verifyWorkerNumReDo(workerNum,scenicId,null);

        /******** 邮箱地址 ********/
        //邮箱地址
        String emailAddress = users.getEmailAddress();

        if(emailAddress!=null && !"".equals(emailAddress)){
            if(!RegExpValidatorUtils.isEmail(emailAddress)){
                throw new BusinessException("mailbox.is.error");
            }
            users.setEmailAddress(emailAddress);
        }

        int result = 0;

        /**  新增 */
        String salt = UUIDUtil.getUUID();
        users.setId(salt)
                .setAccount(phone)
                .setDelFlag((short)0)
                .setUserType(userType)
                .setNickName(nickName)
                .setSex(sex)
                .setPhone(phone)
                .setIdentityCard(identityCard)
                .setAssumeOffice(userType.equals("1")?Short.valueOf("2"):Short.valueOf("1"))
                .setWorkerNum(workerNum)
                .setIsUsing(isUsing)
                .setUserTeamList(userTeamList)
                .setPassword(MD5Util.createPassword(ParamUtil.getValue("defaultPaword"),salt))
                .setCreateTime(new Date())
                .setScenicId(scenicId);
        users.setPassword(MD5Util.createPassword(ParamUtil.getValue("defaultPaword"),salt));
        users.setCreateTime(new Date());
        users.setIsUsing((short)1);
        users.setScenicId(scenicId);

        //原部门经理id
        String originalDirectorId = users.getOriginalDirectorId();

        //新增部门
        this.userTeamService.insertOrUpdate(salt, users.getUserTeamList(),originalDirectorId);
        result = this.mapper.insertSelective(users);

        return result;
    }



    /**
    　* @description: TODO  根据用户ID重置用户密码
    　* @param [uid]
    　* @return int
    　* @throws
    　* @author privatePanda777@163.com
    　* @date 2019/7/25 13:04
    　*/
    public int restPassword(String uid){
	    Users user = new Users();
	    user.setId(uid);
	    user.setPassword(MD5Util.createPassword(ParamUtil.getValue("defaultPaword"),uid));
        int i = this.mapper.updateByPrimaryKeySelective(user);
        return i;
    }

    /**
    　* @description: TODO   根据用户ID查询已领取的所有任务
    　* @param [uid]
    　* @return java.util.List<com.liaoyin.travel.entity.task.Task>
    　* @throws
    　* @author privatePanda777@163.com
    　* @date 2019/7/26 09:51
    　*/
    public List<Task> getTaskListByUid(String uid,Integer num,Integer size,String taskType,String taskLevel,String taskCategories,String taskName){
        if ( null == uid ){
            UserInfo user = PartyUtil.getCurrentUserInfo();
            if(user == null) {
                throw new BusinessException("not.login");
            }
            uid = user.getId();
        }
        PageHelper.startPage(num,size);
        List<Task> tasks = this.taskMapper.selectTaskUserList(uid, null, taskType, taskLevel, taskCategories, taskName);
        for (Task task : tasks) {
            if (null == task.getNickName() || "".equals(task.getNickName())){
                BackUser backUser = this.backUserService.selectBackUserById(task.getUserId());
                System.err.println("backUser="+backUser);
                task.setNickName(backUser.getNickName());
            }
        }
        return tasks;
    }

    /**
    　* @description: TODO    根据任务ID查询任务详情及任务路线
    　* @param [taskId]
    　* @return com.liaoyin.travel.entity.task.TaskDetails
    　* @throws
    　* @author privatePanda777@163.com
    　* @date 2019/7/26 13:07
    　*/
    public TaskDetails selectTaskDetailByTid(String taskId){
        return taskDetailsService.selectTaskDetailByTid(taskId);
    }

    /**
    　* @description: TODO  根据用户ID查询其头像及名称并返回
    　* @param [uid]
    　* @return java.lang.String
    　* @throws
    　* @author privatePanda777@163.com
    　* @date 2019/8/6 15:11
    　*/
    public String selectUserById(String uid){
        Users users = this.mapper.selectByPrimaryKey(uid);
        if (null == users){
            throw new BusinessException("user.isExist");
        }
        String str;
        FileUpload fileUpload = FileUploadUtil.getFileUpload(users.getHeadPicId());
        if (null != fileUpload) {
            str = users.getNickName() + "," + CommonConstant.FILE_SERVER+fileUpload.getFilePath();
        } else {
            str = users.getNickName();
        }
        System.out.println(str);
        return str;
    }

    /**
     * @方法名：uploadLatAndLog
     * @描述： 暂存所有用户的当前位置 => 存入数据库 5分钟上传一次
     * @作者： 周明智
     * @日期： Created in 2019/8/7 14:04
     */
    public void uploadLatAndLog(String uid,String lat,String log,String time,boolean isFirstCall){
        gpsDataMap.put(uid,lat+","+log);
        System.err.println("调用新增运动轨迹接口的时间="+time);
        //查询最近的一条运动轨迹
        MotionTrack motionTrack = this.motionTrackService.selectMotionTrackLastTimeByUserID(uid);
        boolean addOrNot = false;

        if(isFirstCall){
            //如果是刚刚登陆后第一次调用
            addOrNot = true;
        }else{
            //不是刚刚登陆
            if(motionTrack!=null){
                //运动轨迹允许上传的偏移距离
                Double uploadDistanceOfMotionTrack = Double.valueOf(ParamUtil.getValue("uploadDistanceOfMotionTrack"));
                double disparity = LocationUtils.getDistance(Double.valueOf(lat), Double.valueOf(log), Double.valueOf(motionTrack.getuLat()), Double.valueOf(motionTrack.getuLog()));
                System.err.println("上传的经度="+Double.valueOf(lat));
                System.err.println("上传的维度="+Double.valueOf(log));
                System.err.println("最近一条记录的经度="+Double.valueOf(motionTrack.getuLat()));
                System.err.println( "最近一条记录的维度="+Double.valueOf(motionTrack.getuLog()));
                //如果距离大于 允许的偏移距离
                double distance = Math.abs(disparity);
                System.err.println("distance="+distance);
                System.err.println("uploadDistanceOfMotionTrack="+uploadDistanceOfMotionTrack);
                if(distance > uploadDistanceOfMotionTrack) {
                    addOrNot = true;
                }else{
                    System.err.println("距离小于允许新增的偏移距离");
                }
            }else{
                addOrNot = true;
            }
        }

        if(addOrNot){
            System.err.println("新增轨迹成功");
            this.motionTrackService.insertUserLatAndLog(uid, lat, log);
        }else{
            System.err.println("新增轨迹失败");
        }

    }

    /**
    　* @description: TODO  查询物资点 及 客流点
    　* @param [queryType, find]
    　* @return java.util.List<com.liaoyin.travel.entity.attendance.Equipment>
    　* @throws
    　* @author privatePanda777@163.com
    　* @date 2019/8/7 15:07
    　*/
    public List<Equipment> getLatAndLog(Integer queryType,Integer equipmentType,String currentLongitude,String currentLatitude){
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();
        List<Equipment> equipment = null;
        if (queryType == 1 ){
            /** 物资 */
            if (null != equipmentType && !"".equals(equipmentType)){
                equipment = equipmentMapper.selectEquipmentList(equipmentType.toString(),null, "1",scenicId);
            } else {
                Example example = new Example(DictBasic.class);
                example.and().andEqualTo("code","equipmentType").andEqualTo("groupCode",3);
                List<DictBasic> dictBasics = this.dictBasicMapper.selectByExample(example);
                String s = "0" ;
                for (DictBasic dictBasic : dictBasics) {
                    s = s +","+dictBasic.getValue();
                }
                equipment = equipmentMapper.selectEquipmentList(s,"0", "1",scenicId);
            }
        } else if (queryType == 2){
            /** 客流 */
            System.err.println("scenicId="+scenicId);
            equipment = equipmentMapper.selectEquipmentList("4",null, "1",scenicId);
        }
        equipment.forEach(e -> {
            //经度
            String log =  e.getLog();
            //纬度
            String lat = e.getLat();
            //得到当前每一个设备 和 当前位置 的距离
            double distance = LocationUtils.getDisparityByLogAndLat(currentLongitude,currentLatitude,log,lat);
            e.setDisparity(distance);
        });
        //按距离的最近的排序
        equipment.sort(Comparator.comparingDouble(Equipment::getDisparity));
        System.err.println("equipment="+equipment);
        return equipment;
    }

    /**
    　* @description: TODO 获取事件（灾害）的经纬度
    　* @param []
    　* @return java.util.List<com.liaoyin.travel.entity.report.EventReport>
    　* @throws
    　* @author privatePanda777@163.com
    　* @date 2019/8/8 9:11
    　*/
    public List<EventReport> getLatAndLogForEvent(Integer queryType,String currentLongitude,String currentLatitude){
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();
        System.err.println("scenicId="+scenicId);
        Example example = new Example(EventReport.class);
        example.and().andEqualTo("eventProgress",queryType)
                .andEqualTo("scenicId",scenicId);
        List<EventReport> eventReports = this.eventReportMapper.selectByExample(example);
        //计算与当前经纬度的距离
        eventReports.forEach(eventReport -> {
            //经度
            String eventLog = eventReport.getEventLog();
            //纬度
            String eventLat = eventReport.getEventLat();
            //得到当前每一个事件上报 和 当前位置 的距离
            double distance = LocationUtils.getDisparityByLogAndLat(currentLongitude,currentLatitude,eventLog,eventLat);
            eventReport.setDisparity(distance);
        });
        //按距离的最近的排序
        eventReports.sort(Comparator.comparingDouble(EventReport::getDisparity));
        System.err.println("eventReports="+eventReports);
        return  eventReports;
    }

    /**
    　* @description: TODO 获取指定用户的实时经纬度
    　* @param [userId]
    　* @return java.lang.String
    　* @throws
    　* @author privatePanda777@163.com
    　* @date 2019/8/9 12:49
    　*/
    public String getUserLatAndLog(String userId){
        return gpsDataMap.get(userId);
    }

	public static void main(String[] args) {
		System.out.println(MD5Util.createPassword("e10adc3949ba59abbe56e057f20f883e","228daa45bea44982abd1462db10da6a0"));
	}

	/**
	 * @方法名：selectUsersListByTeamId
	 * @描述： 通过部门id查询用户列表
	 * @作者： Kuang.JiaZhuo
	 * @日期： Created in 2019/11/13 18:02
	 */
    public List<Users> selectUsersListByTeamId(String teamId,String scenicId) {
        List<Users> list = this.mapper.selectUsersListByTeamId(teamId,scenicId);
        return list;
    }

    /**
     * @方法名：selectUsersByIds
     * @描述： 通过用户的idList批量查询用户信息
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/19 11:32
     */
    public List<Users> selectUsersByIds(List<String> userIdList) {
        if(userIdList.size()==0){
            return null;
        }
        List<Users> list = this.mapper.selectUsersByIds(userIdList);
        return list;
    }

    /**
     * @方法名：selectUsersByApplicant
     * @描述： 根据请求人的id和发起审批的类型查询审批人的信息
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/22 11:28
     */
    public Users selectUsersByApplicant(String approvalStatus, String userId) {
        Users users = null;
        if(VariableConstants.STRING_CONSTANT_1.equals(approvalStatus)){
            //补卡申请
            String packetId = this.cardReissuePacketApplicantMapper.selectPacketIdByApplicantId(userId);
            users = this.mapper.selectUsersByCardReissuePacketId(packetId);
        }else if(VariableConstants.STRING_CONSTANT_2.equals(approvalStatus)){
            //请假申请
            String packetId = this.askForLeavePacketApplicantMapper.selectPacketIdByApplicantId(userId);
            users = this.mapper.selectUsersByAskForLeavePacketId(packetId);
        }else if(VariableConstants.STRING_CONSTANT_3.equals(approvalStatus)){
            //外出申请
            String packetId = this.goOutPacketApplicantMapper.selectPacketIdByApplicantId(userId);
            users = this.mapper.selectUsersByGoOutPacketId(packetId);
        }
        return users;
    }

    /**
     * @方法名：UserView
     * @描述： 通过用户id返回 UserView
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/23 19:56
     */
    public UserView selectUserViewById(String userId) {
        System.err.println("传入的userId="+userId);
        Users users=  this.mapper.selectUsersById(userId);
        System.err.println("initiatorId="+userId);
        System.err.println("users="+users);
        UserView userView = new UserView();
        System.err.println("userId="+users.getId());
        String userId1 = users.getId();
        //根据用户id查询部门名称
        List<String> teamNames = this.mapper.selectTeamNameByUserId(userId1);
        String teamName = getTeamName(teamNames);
        //部门名称
        userView.setTeamName(teamName);
        String nickName = users.getNickName();
        //头像
        String headPicId = users.getHeadPicId();
        FileUpload fileUpload = FileUploadUtil.getFileUpload(headPicId);
        String headPicUrl = null;
        if(fileUpload!=null){
            headPicUrl = fileUpload.getUrl();
        }
        System.err.println("headPicUrl="+headPicUrl);
        userView.setHeadPicUrl(headPicUrl);
        //职务
        String holdOffice = users.getAssumeOfficeDisplay();
        userView.setHoldOffice(holdOffice);
        userView.setUserId(userId1);
        userView.setNickName(nickName);
        return userView;
    }

    /**
     * @方法名：getTeamName
     * @描述： 传入部门集合得到部门名称
     * @作者： kuang.jiazhuo
     * @日期： Created in 2019/11/27 20:31
     */
    private String getTeamName(List<String> teamNames) {
        if(1==teamNames.size()){
            return teamNames.get(0);
        }
        String result = teamNames.size()+"个部门(";
        for(String teamName:teamNames){
            result+=teamName+",";
        }
        result = result.substring(0,result.length()-1)+")";
        return result;
    }

    /**
     * @方法名：selectNiceNameById
     * @描述： 根据用户id查昵称
     * @作者： kuang.jiazhuo
     * @日期： Created in 2019/11/26 10:24
     */
    public String selectNiceNameById(String userId) {
        String niceName = this.mapper.selectNiceNameById(userId);
        return niceName;
    }

    /**
     * @方法名：notarizeChangeDepartmentManager
     * @描述： 判断该部门是否存在经理 如果已经存在部门负责人会给出弹窗提示
     * @作者： kuang.jiazhuo
     * @日期： Created in 2019/12/3 14:24
     */
    public ChangeManagerView notarizeChangeDepartmentManager(ChangeManagerVo changeManagerVo) {
        ChangeManagerView changeManagerView = new ChangeManagerView();
        //是否要弹框
        boolean popout = false;
        //用户id
        String newDirectorId = changeManagerVo.getId();
        //昵称
        String newNickName = changeManagerVo.getNickName();
        //部门id
        String teamId = changeManagerVo.getTeamId();
        //原部门的经理id
        List<String> originalDirectorIds = this.userTeamService.selectDirectorIdByTeamId(teamId);
        //当前部门经理数量
        int number = originalDirectorIds.size();
        //判断用户id在originalDirectorIds中是否存在
        boolean isExist = originalDirectorIds.contains(newDirectorId);
        if(number>0 && !isExist){
            //弹框提示
            String popoutHint = "该部门已经有【";
            String originalDirectors = "";
            for(String originalDirectorId:originalDirectorIds){
                String originalNickName = this.mapper.selectNiceNameById(originalDirectorId);
                //弹框提示
                originalDirectors += originalNickName+",";
            }
            popoutHint = popoutHint + originalDirectors.substring(0,originalDirectors.length()-1)+"】等"+
                    number+"个部门经理,你确定要继续新增【"+newNickName+"】为项目经理吗？";
            changeManagerView.setPopoutHint(popoutHint);
            popout = true;
        }
        changeManagerView.setPopout(popout);

       return changeManagerView;
    }



    /**
     * @方法名：selectUserListByPhone
     * @描述： 根据电话查询用户信息
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/23 10:54
     */
    public List<Users> selectUserListByPhone(String phone) {
        return this.mapper.selectUserListByPhone(phone);
    }

    /**
     * @方法名：selectScenicIdByUserId
     * @描述： 根据用户id查询用户的景点id
     * @作者： kjz
     * @日期： Created in 2020/2/24 1:48
     */
    public String selectScenicIdByUserId(String userId) {
        return this.mapper.selectScenicIdByUserId(userId);
    }

    /**
     * @方法名：physicsDeleteUsersById
     * @描述： 物理批量删除用户数据
     * @作者： kjz
     * @日期： Created in 2020/2/29 16:04
     */
    @Transactional(rollbackFor=Exception.class)
    public int physicsDeleteUsersById(String uid) {
        String[] split = uid.split(",");
        //删除用户-部门关系
        userTeamMapper.deleteUserTeamByUserIds(split);
        /** 删除关于审批的用户可见关联*/
        //补卡
        cardReissueVisibleUserMapper.deleteCardReissueVisibleUserByUserIds(split);
        //外出
        goOutVisibleUserMapper.deleteGoOutVisibleUserByUserIds(split);
        //请假
        askForLeaveVisibleUserMapper.deleteAskForLeaveVisibleUserByUserIds(split);
        /** 删除考勤和用户的关联,不然删除了之后还是一直有定时任务，又没有scenicId*/
        //考勤用户关联
        attendanceUserMapper.deleteAttendanceUsersByUserIds(split);
        //考勤记录
        attendanceRecordMapper.deleteAttendanceRecordByUserId(split);
       /** 删除用户运动轨迹 */
       motionTrackService.deleteMotionTrackByUserIds(split);
        return this.mapper.physicsDeleteUsersById(split);
    }

    /**
     * @方法名：register
     * @描述： 应急疫情防控申报系统登录
     * @作者： kjz
     * @日期： Created in 2020/3/7 14:25
     */
    public UserInfo register(String phone, String password) {
        if (phone == null || phone.equals("")) {
            throw new BusinessException("phone.is.null");
        }
        UserInfo userInfo = null;
        boolean b = false;

        if (password == null || password.equals("")) {
            throw new BusinessException("password.is.null");
        }
        userInfo = this.mapper.selectUsersByPhone(phone);
        if (userInfo == null) {
            throw new BusinessException("user.isExist");
        }
        if (MD5Util.createPassword(password,userInfo.getId()).equals(userInfo.getPassword())) {
            b = true;
        } else {
            logger.debug(userInfo.getId()+"密码错误");
            throw new BusinessException("password.is.error");
        }
        if (b) {
            userInfo.setPassword(null);
            //生成token
            String token = JwtTokenUtil.createJWT(userInfo.getPhone(), userInfo.getId(), userInfo.getNickName(), null, null, null, 24 * 24 * 60 * 60 * 1000, "123456");
            userInfo.setToken(token);
            //查询用户的部门信息
            List<UserTeam> userTeamList = this.userTeamService.selectUserTeam(userInfo.getId(), "");
            userInfo.setUserTeamList(userTeamList);
            userTeamList=null;
            //将用户信息保存到redis
            RedisUtil.set(userInfo.getPhone() + "#" + userInfo.getId(), JsonUtil.getJsonString(userInfo), jwtTokenUtil.getExpiration());
        } else {
            throw new BusinessException("user.isExist");
        }
        return userInfo;
    }

    /**
     * @方法名：getStaffInfoViewListPage
     * @描述： 获取【修改员工信息接口】的员工数据(带分页)
     * @作者： kjz
     * @日期： Created in 2020/3/31 19:12
     */
    public List<StaffInfoView> getStaffInfoViewListPage(Integer num,Integer size){
        PageHelper.startPage(num,size);
        List<StaffInfoView> list = this.getStaffInfoViewList();
        return list;
    }

    /**
     * @方法名：getStaffInfoViewList
     * @描述： 获取【修改员工信息接口】的员工数据
     * @作者： kjz
     * @日期： Created in 2020/3/31 18:34
     */
    public List<StaffInfoView> getStaffInfoViewList() {
        List<StaffInfoView> list = this.mapper.getStaffInfoViewList();
        list.forEach(staffInfoView -> {
            //用户类型为管理端
            String uDT = staffInfoView.getUDT();
            if(uDT.equals(VariableConstants.STRING_CONSTANT_2)){
                //部门id
                String departId = staffInfoView.getDepartId();
                String workerType = "";
                if(!departId.equals("无")){
                    workerType = this.workerMapper.selectWorkerNameByTeamId(departId);
                }
                staffInfoView.setWorkerType(workerType);
            }

        });

        return list;
    }

    /**
     * @方法名：selectNewMailListByScale
     * @描述： APP用户登录后查询自己所在的部门通讯录
     * @作者： kjz
     * @日期： Created in 2020/4/16 11:10
     */
    public ClassificationInfo selectNewMailListByScale() {
        UserInfo activeUser = PartyUtil.getCurrentUserInfo();
        Optional.ofNullable(activeUser).orElseThrow(() -> new BusinessException("not.login"));

        List<UserTeam> userTeamList = activeUser.getUserTeamList();
        if(userTeamList==null || userTeamList.size() == 0) {
            throw new BusinessException("team.is.null");
        }

        String teamId = userTeamList.get(0).getTeamId();
        Team team = this.teamService.selectTeamById(teamId);
        List<Users> usersList = this.mapper.selectUsersListOnTeamById(teamId);
        System.err.println("----查询到的用户的数据----");
        System.err.println(JSON.toJSON(usersList));
        usersList.forEach(users -> {
            String headPidId = users.getHeadPicId();
            headPidId = headPidId==null || headPidId.equals("") ? appHeadPortraitBusinessId : headPidId;
            System.err.println("headPidId="+headPidId);
            FileUpload fileUpload = FileUploadUtil.getFileUpload(headPidId);
            fileUpload = fileUpload==null?new FileUpload():fileUpload;
            users.setFileUpload(fileUpload);
        });

        ClassificationInfo classificationInfo = new ClassificationInfo()
                .setTeam(team).setDepartmentalStaffs(usersList);

        System.err.println("----通讯录打印----");
        System.err.println(JSON.toJSON(classificationInfo));
        return classificationInfo;
    }

    /**
     * @方法名：selectMailListByTeamId
     * @描述： 根据部门id查询下级部门的通讯录
     * @作者： kjz
     * @日期： Created in 2020/4/16 11:32
     */
    public List<ClassificationInfo> selectMailListByTeamId(String teamId) {
        List<Team> teamList = this.teamService.selectTeamByParentId(teamId);
        List<ClassificationInfo> list = new ArrayList<>();
        for(Team team:teamList){
            List<Users> userList = this.mapper.selectUsersListOnTeamById(team.getId());
            //头像
            userList.forEach(users -> {
                String headPidId = users.getHeadPicId();
                headPidId = headPidId==null || headPidId.equals("") ? appHeadPortraitBusinessId : headPidId;
                FileUpload fileUpload = FileUploadUtil.getFileUpload(headPidId);
                fileUpload = fileUpload==null?new FileUpload():fileUpload;
                users.setFileUpload(fileUpload);
            });
            ClassificationInfo classificationInfo = new ClassificationInfo()
                    .setTeam(team).setDepartmentalStaffs(userList);
            list.add(classificationInfo);
            }
        return list;
    }

    /**
     * @方法名：selectMailListByScale
     * @描述： 登陆用户查询自己的部门通讯录(递归得到所有的部门员工通讯录)
     * @作者： kjz
     * @日期： Created in 2020/4/8 17:42
     */
    public ScaleUserView selectMailListByScale() {
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if (user == null) {
            throw new BusinessException("not.login");
        }

        ScaleUserView scaleUserView = new ScaleUserView();

        List<UserTeam> userTeamList = user.getUserTeamList();
        if(userTeamList==null || userTeamList.size() == 0) {
            throw new BusinessException("team.is.null");
        }
        String teamId = userTeamList.get(0).getTeamId();
        Team team = this.teamService.selectTeamById(teamId);
        //部门级别
        Short teamLevel = team.getTeamLevel();

        //返回结果
        ClassificationInfo firstOrderUsers = new ClassificationInfo();
        List<ClassificationInfo> twoOrderUsers = new ArrayList<>();
        List<ClassificationInfo> threeOrderUsers = new ArrayList<>();

        List<Team> twoTeamList = new ArrayList<>();
        //一级部门
        if(teamLevel==1){
            List<Users> firstUsers = this.mapper.selectUsersListOnTeamById(teamId);
            firstUsers.forEach(users -> {
                String headPidId = users.getHeadPicId();
                headPidId = headPidId==null || headPidId.equals("") ? appHeadPortraitBusinessId : headPidId;
                System.err.println("headPidId="+headPidId);
                FileUpload fileUpload = FileUploadUtil.getFileUpload(headPidId);
                fileUpload = fileUpload==null?new FileUpload():fileUpload;
                users.setFileUpload(fileUpload);
            });
            firstOrderUsers.setTeam(team).setDepartmentalStaffs(firstUsers);

            twoTeamList = this.teamService.selectTeamByParentId(teamId);

            twoOrderUsers = this.getTwoOrderUsers(twoTeamList);
            threeOrderUsers = this.getThreeOrderUsers(twoTeamList);

            //一级部门信息
        }
        //二级部门
        if(teamLevel==2){

            List<Users> userList = this.mapper.selectUsersListOnTeamById(teamId);

            ClassificationInfo classificationInfo = new ClassificationInfo()
                    .setDepartmentalStaffs(userList).setTeam(team);
            twoOrderUsers.add(classificationInfo);

            twoTeamList.add(team);
            threeOrderUsers = this.getThreeOrderUsers(twoTeamList);
        }
        //三级部门
        if(teamLevel==3){
            List<Users> userList = this.mapper.selectUsersListOnTeamById(teamId);
            ClassificationInfo classificationInfo = new ClassificationInfo()
                    .setDepartmentalStaffs(userList).setTeam(team);
            threeOrderUsers.add(classificationInfo);
        }

        scaleUserView.setFirstOrderUsers(firstOrderUsers)
                .setTwoOrderUsers(twoOrderUsers)
                .setThreeOrderUsers(threeOrderUsers);

        return scaleUserView;
    }

    /**
     * @方法名：getThreeOrderUsers
     * @描述： 获取三级部门的员工信息
     * @作者： kjz
     * @日期： Created in 2020/4/8 18:55
     */
    public List<ClassificationInfo> getThreeOrderUsers(List<Team> twoTeamList) {
        List<ClassificationInfo> threeOrderUsers = new ArrayList<>();
        for(Team team:twoTeamList){
            List<Team> threeTeams = this.teamService.selectTeamByParentId(team.getId());
            for(Team threeTeam:threeTeams){
                List<Users> userList = this.mapper.selectUsersListOnTeamById(threeTeam.getId());
                //头像
                userList.forEach(users -> {
                    String headPidId = users.getHeadPicId();
                    headPidId = headPidId==null || headPidId.equals("") ? appHeadPortraitBusinessId : headPidId;
                    FileUpload fileUpload = FileUploadUtil.getFileUpload(headPidId);
                    fileUpload = fileUpload==null?new FileUpload():fileUpload;
                    users.setFileUpload(fileUpload);
                });
                ClassificationInfo classificationInfo = new ClassificationInfo()
                        .setTeam(threeTeam).setDepartmentalStaffs(userList);
                threeOrderUsers.add(classificationInfo);
            }
        }
        return threeOrderUsers;
    }

    /**
     * @方法名：getTwoOrderUsers
     * @描述： 获取二级部门的员工信息
     * @作者： kjz
     * @日期： Created in 2020/4/8 18:51
     */
    public List<ClassificationInfo> getTwoOrderUsers(List<Team> twoTeamList) {
        List<ClassificationInfo> twoOrderUsers = new ArrayList<>();
        for(Team team:twoTeamList){
            List<Users> userList = this.mapper.selectUsersListOnTeamById(team.getId());
            //头像
            userList.forEach(users -> {
                String headPidId = users.getHeadPicId();
                headPidId = headPidId==null || headPidId.equals("") ? appHeadPortraitBusinessId : headPidId;
                FileUpload fileUpload = FileUploadUtil.getFileUpload(headPidId);
                fileUpload = fileUpload==null?new FileUpload():fileUpload;
                users.setFileUpload(fileUpload);
            });
            ClassificationInfo classificationInfo = new ClassificationInfo()
                    .setTeam(team).setDepartmentalStaffs(userList);
            twoOrderUsers.add(classificationInfo);
        }
       return twoOrderUsers;
    }

    /**
     * @方法名：selectFromUserIdByUserId
     * @描述： 通过用户id查询推送的昵称
     * @作者： kjz
     * @日期： Created in 2020/4/13 19:40
     */
    public String selectFromUserIdByUserId(String userId) {
        BackUser backUser = this.backUserService.selectBackUserById(userId);
        if(backUser==null){
            return userId;
        }
        return backUser.getNickName()+"(后台管理员)";
    }

    /**
     * @方法名：refreshUserData
     * @描述： 传入用户id获取用户信息
     * @作者： kjz
     * @日期： Created in 2020/4/17 14:39
     */
    public UserInfo refreshUserData(String userId) {
        if (userId == null && !userId.equals("")){
            throw new BusinessException("id.is.null","用户id为空");
        }
        //获取当前登录用户信息
        UserInfo currentUser = PartyUtil.getCurrentUserInfo();
        Optional.ofNullable(currentUser).orElseThrow(() -> new BusinessException("not.login"));

        UserInfo newestUserInfo = this.mapper.selectUsersByFingerprint(userId);
        Optional.ofNullable(newestUserInfo).orElseThrow(() -> new BusinessException("user.isExist"));

        newestUserInfo.setPassword(null);
        //查询用户的部门信息
        List<UserTeam> userTeamList = this.userTeamService.selectUserTeam(userId, "");
        newestUserInfo.setUserTeamList(userTeamList);

        return newestUserInfo;

    }

    /**
     * @方法名：getIfThereIsAViewByIsSpecifyAndBusinessId
     * @描述： 根据指定类型和businessId查询指定的【人员/部门/工种】是否存在
     * @作者： kjz
     * @日期： Created in 2020/4/21 20:39
     */
    public IfThereIsAView getIfThereIsAViewByIsSpecifyAndBusinessId(Short isSpecify, String businessId) {
        boolean isExist = true;
        String notExistCause = null;
        List<String> businessIdList = Arrays.asList(businessId.split(","));

        /** 按人员指定 **/
        if(isSpecify.intValue()==1){
            List<Users> list = this.mapper.selectUsersListByUserIds(businessIdList);
            if(list==null || list.size()==0){
                isExist = false;
                //不存在
                notExistCause = VariableConstants.STRING_CONSTANT_1;
            }else{
                int count = 0;
                for(Users users:list){
                    if(users.getIsUsing()==0){
                        count +=1;
                    }
                }
               if(count==list.size()){
                   isExist = false;
                   //被禁用
                   notExistCause =  VariableConstants.STRING_CONSTANT_2;
               }
            }
        }

        /** 按部门指定 **/
        if(isSpecify.intValue()==2){
            List<Team> list = this.teamMapper.selectTeamByIds(businessIdList);
            if(list==null || list.size()==0){
                isExist = false;
                //不存在
                notExistCause = VariableConstants.STRING_CONSTANT_1;
            }else{
                int count = 0;
                for(Team team:list){
                    if(team.getIsUsing()==0){
                        count +=1;
                    }
                }
                if(count==list.size()){
                    isExist = false;
                    //被禁用
                    notExistCause =  VariableConstants.STRING_CONSTANT_2;
                }
            }
        }

        /** 按工种指定 **/
        if(isSpecify.intValue()==3){
            List<Worker> list = this.workerMapper.selectWorkerByIds(businessIdList);
            if(list==null || list.size()==0){
                isExist = false;
                //不存在
                notExistCause = VariableConstants.STRING_CONSTANT_1;
            }else{
                int count = 0;
                for(Worker worker:list){
                    if(worker.getIsUsing()==0){
                        count +=1;
                    }
                }
                if(count==list.size()){
                    isExist = false;
                    //被禁用
                    notExistCause =  VariableConstants.STRING_CONSTANT_2;
                }
            }
        }

        IfThereIsAView ifThereIsAView = new IfThereIsAView()
                .setExist(isExist)
                .setNotExistCause(notExistCause);

        return ifThereIsAView;
    }
}


